package cn.itcast.filter;

import cn.itcast.domain.Admin;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //转成HttpservletRequest 和 HttpServletResponse对象 ,用于获取session
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //获取域中的数据
        Admin admin = (Admin) req.getSession().getAttribute("admin");

        //要放行的资源路径
        String sp = req.getServletPath();

        if (admin !=null || "/login.jsp" .equals(sp) || "/admin".equals(sp)){
            chain.doFilter(req,resp);
        }else{//没有登录,提示并6s后返回登录页面
            String str  = "<h1 align='center'><a href='/web_project01/login.jsp' style='text-decoration:none;'  >点我登录或者5秒后自动跳到登录,你奈我何???</a></h1>";
            resp.getWriter().write(str);
            resp.setHeader("Refresh","6;URL=/web_project01/login.jsp");
        }
    }

    @Override
    public void destroy() {

    }
}
